<?php

namespace app\admin\controller\questionnaire\result;

use app\admin\service\TaskService;
use app\admin\service\UserService;
use app\BaseController;
use app\model\not_del\DepartmentModel as NotDelDepartmentModel;
use app\model\not_del\UserModel as NotDelUserModel;
use app\model\questionnaire\QuestionnairePaperModel;
use app\model\questionnaire\QuestionnaireTaskModel;
use app\model\questionnaire\QuestionnaireTaskPaperModel;
use app\model\questionnaire\QuestionnaireTaskUserModel;
use app\model\questionnaire\QuestionnaireTaskUserResultModel;
use app\model\UnitModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 发布人选择器
     * @return bool|string
     */
    public function publisherSelector(): bool|string
    {
        try {
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            $uid = $QuestionnaireTaskModel->where('unit_id', '=', $this->userData['unit_id'])->column('uid');
            $UserModel = new NotDelUserModel();
            $data = $UserModel->where('id', 'in', $uid)->field('id,name')->select();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 答卷结果列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'pageSize|每页显示数量' => 'require'
            ]);
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['start_time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['start_time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['start_time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['uid'])) {
                $where[] = ['uid', '=', $param['uid']];
            }
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $TaskIds = $QuestionnaireTaskUserResultModel->where('unit_id', '=', $this->userData['unit_id'])->column('task_id');
            if (count($TaskIds) > 0) {
                $where[] = ['id', 'in', $TaskIds];
            } else {
                $where[] = ['id', '=', -1];
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            $query = $QuestionnaireTaskModel->where($where);
            $data = $query->with([
                'user'
            ])->order('id desc')->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 获取任务试卷
     * @return false|string
     */
    public function getTaskPaper(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $QuestionnaireTaskPaperModel = new QuestionnaireTaskPaperModel();
            $data = $QuestionnaireTaskPaperModel->with(['paper'])->where('task_id', '=', $id)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取任务用户
     * @return false|string
     */
    public function getTaskUser(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $data = $this->getTaskUser2($id);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function getTaskUser2($id): array
    {
        $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
        $data = $QuestionnaireTaskUserModel->field('uid,is_finish')->where('task_id', '=', $id)->with([
            'taskUser'
        ])->order('is_finish', 'asc')->group('uid')->select()->toArray();
        $departmentIds = array_column($data, 'department_id');
        $UserService = new UserService($this->app);
        $NotDelDepartmentAll = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
        $DepartmentAdminAll = $UserService->getDepartmentAdminAll($departmentIds);
        foreach ($data as &$item) {
            $item['department_name'] = $NotDelDepartmentAll[$item['department_id']]['all_name'] ?? '';
            $item['department_admin'] = $DepartmentAdminAll[$item['department_id']]['user_name'] ?? '--';
        }
        return $data;
    }

    /**
     * 导出任务用户名单
     * @return false|string
     */
    public function exportTaskUser(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|任务ID' => 'require',
                'is_finish|参与状态' => 'require',
            ]);
            $data = $this->getTaskUser2($param['id']);
            $TaskService = new TaskService($this->app);
            return success($TaskService->exportTaskUser($data,$param['is_finish']));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 答卷结果整体概况
     * @return bool|string
     */
    public function taskOverview(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $QuestionnaireTaskPaperModel = new QuestionnaireTaskPaperModel();
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $list = $QuestionnaireTaskPaperModel->where('task_id', '=', $id)
                ->with([
                    'paper' => function ($query) {
                        $query->with(['typeName']);
                    },
                ])->select()->toArray();
            foreach ($list as &$item){
                $scoreList = $QuestionnaireTaskUserResultModel->where([
                    ['task_id', '=', $item['task_id']],
                    ['paper_id', '=', $item['paper_id']],
                ])->column('total_score');
                $score_count = count($scoreList);//已做问卷数量
                $total_score = array_sum($scoreList);//所有问卷总得分
                $item['average'] = $total_score > 0 ? round($total_score / $score_count, 2) : 0;
            }
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            $TaskInfo = $QuestionnaireTaskModel->with([
                'user' => function ($query) {
                    $query->with(['roleName']);
                }
            ])->find($id)->toArray();
            $TaskInfo['result_count'] = $QuestionnaireTaskUserResultModel->where('task_id', '=', $id)->count();
            $TaskInfo['pass_result_count'] = $QuestionnaireTaskUserResultModel->where([
                ['task_id', '=', $id],
                ['is_pass', '=', 1],
            ])->count();
            if (empty($TaskInfo['role_name'])) $TaskInfo['role_name'] = '超级管理员';
            return success([
                'TaskInfo' => $TaskInfo,
                'list' => $list
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 问卷结果-左测概况
     * @return bool|string
     */
    public function taskPaperLeftSurvey(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $QuestionnaireTaskPaperModel = new QuestionnaireTaskPaperModel();
            $info = $QuestionnaireTaskPaperModel->with([
                'paper' => function ($query) {
                    $query->with(['typeName']);
                },
                'task'])->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $scoreList = $QuestionnaireTaskUserResultModel->where([
                ['task_id', '=', $info['task_id']],
                ['paper_id', '=', $info['paper_id']],
            ])->column('total_score');
            $score_count = count($scoreList);//已做问卷数量
            $total_score = array_sum($scoreList);//所有问卷总得分
            //平均分
            $info['average'] = $total_score > 0 ? round($total_score / $score_count, 2) : 0;
            //最高分
            $info['max'] = max($scoreList);
            //最低分
            $info['min'] = min($scoreList);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 任务用户部门树
     * @return bool|string
     */
    public function taskUserDepartment(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'task_id|任务ID' => 'require',
                'paper_id|问卷ID' => 'require'
            ]);
            $where = [];
            $where[] = ['task_id', '=', $param['task_id']];
            $where[] = ['paper_id', '=', $param['paper_id']];
            //查询满足条件报告
            $whereResult = [];
            if (isset($param['is_comment']) && strlen($param['is_comment']) > 0) {
                $whereResult[] = ['is_comment', '=', $param['is_comment']];
            }
            if (!empty($whereResult)) {
                $whereResult[] = ['task_id', '=', $param['task_id']];
                $whereResult[] = ['paper_id', '=', $param['paper_id']];
                $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
                $ResultIds = $QuestionnaireTaskUserResultModel->where($whereResult)->column('id');
                if (!empty($ResultIds)) {
                    $where[] = ['result_id', 'in', $ResultIds];
                } else {
                    $where[] = ['result_id', '=', -1];
                }
            }
            if (!empty($param['name']) && !empty($param['sex'])) {
                $UserModel = new NotDelUserModel();
                $uids = $UserModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['role_mode','=',3],
                    ['name', 'like', '%' . $param['name'] . '%'],
                    ['sex', '=', $param['sex']]
                ])->column('id');
                if (!empty($uids)) {
                    $where[] = ['uid', 'in', $uids];
                } else {
                    $where[] = ['id', '=', -1];
                }
            } else {
                if (!empty($param['name'])) {
                    $UserModel = new NotDelUserModel();
                    $uids = $UserModel->where([
                        ['unit_id','=',$this->userData['unit_id']],
                        ['role_mode','=',3],
                        ['name', 'like', '%' . $param['name'] . '%'],
                    ])->column('id');
                    if (!empty($uids)) {
                        $where[] = ['uid', 'in', $uids];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                }
                if (!empty($param['sex'])) {
                    $UserModel = new NotDelUserModel();
                    $uids = $UserModel->where([
                        ['unit_id','=',$this->userData['unit_id']],
                        ['role_mode','=',3],
                        ['sex', '=', $param['sex']]
                    ])->column('id');
                    if (!empty($uids)) {
                        $where[] = ['uid', 'in', $uids];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                }
            }
            $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
            $user = $QuestionnaireTaskUserModel->field('id,uid,result_id')->where($where)
                ->with(['user2', 'TaskUserResult'])->select()->toArray();
            $departmentIds = array_column($user, 'department_id');
            $departmentData = [];
            foreach ($user as $item) {
                $departmentData[$item['department_id']]['user_list'][] = $item;
            }
            $UserService = new UserService($this->app);
            if (!empty($param['unit_id'])) {
                $departmentIds = $UserService->getDepartmentAuthId($param['unit_id'], $departmentIds);
            } else {
                $departmentIds = $UserService->getDepartmentAuthId($this->userData['unit_id'], $departmentIds);
            }
            $DepartmentModel = new NotDelDepartmentModel();
            $data = $DepartmentModel->field('id,pid,name')
                ->where('id', 'in', $departmentIds)->select()->toArray();
            foreach ($data as &$item) {
                $item['user_list'] = $departmentData[$item['id']]['user_list'] ?? [];
                if (!empty($param['sort'])) {
                    $field = [];
                    foreach ($item['user_list'] as $key => $row) {
                        $field[$key] = $row['result_total_score'];
                    }
                    switch ($param['sort']) {
                        case "asc":
                            array_multisort($field, SORT_ASC, $item['user_list']); // 假设按’field’字段升序排序
                            break;
                        case "desc":
                            array_multisort($field, SORT_DESC, $item['user_list']);
                            break;
                    }
                }
            }
            $data2 = buildTree($data);
            if (empty($data2)) {
                $data3 = [];
            } else {
                if (!empty($param['unit_id'])) {
                    $UnitModel = new UnitModel();
                    $data3[] = [
                        'id' => 0,
                        'name' => $UnitModel->where('id', '=', $param['unit_id'])->value('name') ?? '',
                        'child' => $data2,
                        'user_list' => []
                    ];
                } else {
                    $data3[] = [
                        'id' => 0,
                        'name' => $this->userData['unit']['name'] ?? '',
                        'child' => $data2,
                        'user_list' => []
                    ];
                }
            }
            return success($data3);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 结果详情
     * @return bool|string
     */
    public function resultInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require'
            ]);
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $info = $QuestionnaireTaskUserResultModel->with([
                'user' => function ($query) {
                    $query->with(['role_name']);
                },
                'paper' => function ($query) {
                    $query->with([
                        'typeName',
                        'paperTopic' => function ($query) {
                            $query->with([
                                'topic' => function ($query) {
                                    $query->with(['answer', 'img']);
                                }
                            ]);
                        }
                    ]);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('未找到结果！');
            $info = $info->toArray();
            if ($info['admin_del'] == 1) throw new \Exception('已被删除！');
            $question_answer = json_decode($info['question_answer'], true);
            $answerData = [];
            foreach ($question_answer as $v) {
                $answerData[$v['topic_id']] = $v;
            }
            foreach ($info['paperTopic'] as &$item) {
                $item['topic']['question_answer'] = $answerData[$item['topic']['id']] ?? [];
            }
            $UserService = new UserService($this->app);
            $info['department_name'] = $UserService->getNotDelDepartmentName($this->userData['unit_id'], $info['department_id']);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 结果点评
     * @return bool|string
     */
    public function comment(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require|integer',
                'comment|点评' => 'require',
//                'score|得分' => 'require'
            ]);
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $info = $QuestionnaireTaskUserResultModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['score'])) {
                $question_answer = json_decode($info['question_answer'], true);
                $score = [];
                foreach ($param['score'] as $v) {
                    $score[$v['topic_id']] = $v;
                }
                foreach ($question_answer as &$item) {
                    if ($item['type'] == 5) {
                        if (isset($score[$item['topic_id']])) {
                            $item['score'] = $score[$item['topic_id']]['score'] ?? 0;
                        }
                    }
                }
                $info->total_score = array_sum(array_column($question_answer, 'score'));
                $info->question_answer = json_encode($question_answer, true);
            }
            //问卷
            $QuestionnairePaperModel = new QuestionnairePaperModel();
            $PaperInfo = $QuestionnairePaperModel->find($info['paper_id']);
            if ($info->total_score >= $PaperInfo['pass_score']) {
                $info->is_pass = 1;
            } else {
                $info->is_pass = 0;
            }
            $info->is_valid = 1;
            $info->comment = $param['comment'];
            $info->is_comment = 1;
            $info->save();
            return success($info->total_score);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 修改权限
     * @return bool|string
     */
    public function resultReadAuth(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'result_read_auth|权限' => 'require'
            ]);
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            $QuestionnaireTaskModel->where('id', 'in', $param['id'])->update([
                'result_read_auth' => $param['result_read_auth']
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除整个任务的报告
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require'
            ]);
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            if (is_array($param['id'])) {
                $QuestionnaireTaskUserResultModel->where('task_id', 'in', $param['id'])->update([
                    'admin_del' => 1
                ]);
            } else {
                $QuestionnaireTaskUserResultModel->where('task_id', '=', $param['id'])->update([
                    'admin_del' => 1
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 删除任务单个问卷的全部报告
     * @return bool|string
     */
    public function taskPaperResultDel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'paper_id|问卷ID' => 'require'
            ]);
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $QuestionnaireTaskUserResultModel->where([
                ['task_id', '=', $param['id']],
                ['paper_id', '=', $param['paper_id']],
            ])->update([
                'admin_del' => 1
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除单份报告
     * @return bool|string
     */
    public function resultDel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require'
            ]);
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $info = $QuestionnaireTaskUserResultModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save([
                'admin_del' => 1
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}